React 中 event 的使用方式和原生 JS 有所不同,主要是以下幾點差異
DOM 元素的事件屬性名稱都是小寫,例如 onclick,而 React 中則是駝峰式命名,例如 onClick。string,例如 onclick="send",而在 React 中則是函式,例如 onClick={ this.testFunction2.bind(this) }。false 來阻止瀏覽器默認行為,而 React 中必須在函式內使用 preventDefault() 來停止默認行為。React 內建函式的 this 都是指向 React 元件本身,但若使用自己建立的函式時,必須使用 bind 來綁定 this,這樣 this 才會指向元件本身,若是沒有綁定,那在函式中 console this,會發現 this 為 undefined
class UserProfile extends React.Component {
testFunction () {
console.log(this) // undefined
}
testFunction2 () {
console.log(this) // 指向 UserProfile
}
render () {
return <div>
<button onClick={this.testFunction}>submit</button>
<button onClick={this.testFunction2.bind(this)}>submit</button>
</div>
}
}
或是也可以在 constructor 之中綁定 this,這其實是常見的作法之一,只是在 create-react-app 中因為支援不使用 constructor,所以課程中是使用前述的方法。
class UserProfile extends React.Component {
constructor () {
super()
this.testFunction = this.testFunction.bind(this)
}
testFunction (e) {
console.log(e)
console.log(this) //指向 UserProfile
}
render () {
return <div>
<button onClick={ this.testFunction}>submit</button>
</div>
}
}
若是不想使用 bind 寫法,其實也可以透過回調函數的方式來綁定,這個方式有一個缺點是每次元件 render 時,都會產生一個新的 callback function,但是它使用上較為直觀,如下
class UserProfile extends React.Component {
testFunction () {
console.log(this) // UserProfile
}
render () {
return <div>
<button onClick={ e => this.testFunction(e)}>submit</button>
</div>
}
}
還有一個比較新的方式,是還在實驗階段的 class fields 語法,使用這個語法需要安裝對應的 babel plugin,不過 create-react-app 中有默認支援,因此不用安裝。它基本上是利用了 arrow function 的 this 指向特性去綁定 event,是 React 官方比較推薦的 event 處理方式。
class UserProfile extends React.Component {
constructor () {
super()
}
testFunction = (e) => {
console.log(e)
console.log(this) // UserProfile
}
render () {
return <div>
<button onClick={ this.testFunction}>submit</button>
</div>
}
}
在 React 的 event 中傳遞參數有幾種寫法,以 class component 來說有下面幾種寫法,分別是透過 bind、回掉函式及匿名函式,都能達到一樣的效果
class UserProfile extends React.Component {
testFunction (e) {
console.log(e)
console.log(this)
}
render () {
return <div>
<button onClick={ this.testFunction.bind(this, 'test')}>submit</button>
<button onClick={ e => this.testFunction('test', e)}>submit</button>
<button onClick={ () => this.testFunction('test')}>submit</button>
</div>
}
}
在 function component 中,因為不能使用 this 調用函式,只能用 bind 及匿名函式來處理
const UserProfile = () => {
const testFunction = (e) => {
console.log(e)
}
return <div>
<button onClick={ testFunction.bind(this, 'test')}>submit</button>
<button onClick={ () => testFunction('test')}>submit</button>
</div>
}
React 中提供阻止默認行為的方法,就是透過 preventDefault 來阻擋,如下面透過 preventDefault,阻止連結跳轉。
const UserProfile = () => {
const testFunction = (e) => {
console.log(e)
e.preventDefault() // 阻止默認行為
}
return <div>
<a href="https://www.google.com/" onClick={e => testFunction(e)}>google</a>
</div>
}
這一篇我們簡單整理了 React 中處理 event 的方式,以及 event 傳遞參數和組止默認行為的方式。